package com.dissertation.service.impl;

import com.dissertation.annotation.AdminAuth;
import com.dissertation.annotation.AdminOrTeacherAuth;
import com.dissertation.annotation.AllUserAuth;
import com.dissertation.model.Template;
import com.dissertation.model.auth.User;
import com.dissertation.pojo.UserVO;
import com.dissertation.respository.UserRepository;
import com.dissertation.service.UserService;
import com.dissertation.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import java.util.*;

import static com.dissertation.model.auth.Role.ADMIN;
import static com.dissertation.model.auth.Role.STUDENT;
import static com.dissertation.model.auth.Role.TEACHER;
import static org.springframework.data.mongodb.core.query.Criteria.where;

@Service
public class UserImpl implements UserService {

    @Autowired
    UserRepository userRepository;
    @Autowired
    MongoTemplate template;

    @AdminAuth
    @Override
    public String addUser(UserVO userVO) {
        User user = new User();
        user.setUniqueName(userVO.getUniqueName());
        user.setPassword(MD5Util.toMD5(userVO.getPassword()));
        List<String> list = userVO.getRole();
        for(String role : list){
            if(role.equals("student")){
                user.addRoles(STUDENT);
            }
             else if(role.equals("teacher")){
                user.addRoles(TEACHER);
            }
              else if(role.equals("admin")){
                user.addRoles(ADMIN);
            }
            else return "error role";
        }
        user = userRepository.save(user);
        return user.getId();
    }

    @AllUserAuth
    @Override
    public Object changePwd(String uniqueName , String password) {
        String newPassword = MD5Util.toMD5(password);
        Query query = Query.query( where( "uniqueName" ).is(uniqueName));
        return template.updateFirst(query, new Update().set("password", newPassword), User.class).getN();
    }
}
